package com.nineclock.attendance.task;

import com.nineclock.attendance.mapper.AttendGroupMapper;
import com.nineclock.attendance.pojo.AttendGroup;
import com.nineclock.attendance.service.AttendPunchService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysCompanyUserFeign;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 发送邮件定时任务类
 */
@Component
@Slf4j
public class SendAttendMailTask {

    @Autowired
    private AttendGroupMapper attendGroupMapper;

    @Autowired
    private AttendPunchService attendPunchService;

    @Autowired
    private SysCompanyUserFeign companyUserFeign;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @XxlJob("demoJobHandler")
    public void countAttendanceAndSendMail() throws Exception{
        log.info("---定时发送考勤报表给企业管理员---");

        // 1.获取所有企业id(设置了考勤组)
        Set<Long> companyIds = this.queryAllCompanyIds();
        
        if(!CollectionUtils.isEmpty(companyIds)){
            for (Long companyId : companyIds) {

                // 统计每个公司的考勤报表，生成excel
                String excelPath = attendPunchService.generatePunchReport(companyId);

                // 给每个公司的企业管理员发送邮件
                SysCompanyUserDTO admin = companyUserFeign.queryAdminByCompanyId(companyId).getData();
                if(admin!=null && !StringUtils.isEmpty(admin.getEmail())){
                    this.sendMail(admin, excelPath);
                }

            }
        }
    }

    /**
     * 发送邮件
     */
    private void sendMail(SysCompanyUserDTO admin, String excelPath) throws Exception{
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
        messageHelper.setFrom(from); // 发送者邮箱
        messageHelper.setSubject("考勤数据报表"); // 邮件标题
        messageHelper.setText("您好, 本月考勤数据报表已经生成, 请查收附件, 谢谢"); // 邮件内容
        messageHelper.setTo(admin.getEmail()); // 收件者邮箱

        messageHelper.addAttachment("考勤报表.xls", new File(excelPath));

        javaMailSender.send(mimeMessage);
    }

    /**
     * 获取所有企业id(设置了考勤组)
     * @return
     */
    private Set<Long> queryAllCompanyIds(){
        List<AttendGroup> attendGroupList = attendGroupMapper.selectList(null);
        
        if(!CollectionUtils.isEmpty(attendGroupList)){
            Set<Long> companyIds = attendGroupList.stream().map(attendGroup -> {
                return attendGroup.getCompanyId();
            }).collect(Collectors.toSet());
            return companyIds;
        }

        return null;
    }
}
